//
//  WJTabBar.m
//  BeDeJie
//
//  Created by jerry on 2017/1/25.
//  Copyright © 2017年 jerry. All rights reserved.
//

#import "WJTabBar.h"
#import "WJPublishViewController.h"

@interface WJTabBar()

//发布按钮
@property (nonatomic, weak) UIButton *plusButton;
//上一次点击的按钮
@property (nonatomic, weak) UIControl *previousClickedTabBarButton;

@end

@implementation WJTabBar


//懒加载发布按钮
-(UIButton *)plusButton {
    if(_plusButton == nil){
        
        //发布按钮添加到TabBar上
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setImage:[UIImage imageNamed:@"icon_tabBar_publish_normal"] forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:@"icon_tabBar_publish_selected"] forState:UIControlStateHighlighted];
        [btn sizeToFit];
        [self addSubview:btn];
        
        _plusButton = btn;
    }
    return _plusButton;
}

//对子控件重新布局
-(void) layoutSubviews {
    [super layoutSubviews];
    
    //计算TabBar中子控件的数量
    NSInteger count = self.items.count;
    //单个TabBarButton的宽度
    CGFloat btnWidth = self.frame.size.width / (count + 1);
    //单个TabBarButton的高度
    CGFloat btnHeight = self.frame.size.height;
    CGFloat btnX = 0;
    
    //遍历子控件，调整布局
    int i = 0;
    for (UIControl *tabBarButton in self.subviews) {
        //反射获取UITabBarButton的class
        if ([tabBarButton isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
            // 设置previousClickedTabBarButton默认值为最前面的按钮
            if (i == 0 && self.previousClickedTabBarButton == nil) {
                self.previousClickedTabBarButton = tabBarButton;
            }
            
            //对发布按钮做特殊处理
            if (i == 2) {
                i += 1;
            }
            btnX = i * btnWidth;
            
            tabBarButton.frame = CGRectMake(btnX, 0, btnWidth, btnHeight);
            i++;
            
            // 监听点击
            [tabBarButton addTarget:self action:@selector(tabBarButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        }
    }
    
    //调整发布按钮的位置
    self.plusButton.center = CGPointMake(self.frame.size.width * 0.5, self.frame.size.height * 0.5);
    //点击发布按钮
    [self.plusButton addTarget:self action:@selector(publishButtonClick:) forControlEvents:UIControlEventTouchUpInside];
}

//tabBarButton的点击
- (void)tabBarButtonClick:(UIControl *)tabBarButton{
    
    if (self.previousClickedTabBarButton == tabBarButton) {
        // 发出通知，告知外界tabBarButton被重复点击了
        [[NSNotificationCenter defaultCenter] postNotificationName:WJTabBarButtonDidRepeatClickNotification object:nil];
    }
    
    self.previousClickedTabBarButton = tabBarButton;
}

- (void)publishButtonClick:(UIControl *)tabBarButton{
    
    WJPublishViewController *publishViewController = [[WJPublishViewController alloc] init];
    [self.window.rootViewController presentViewController:publishViewController animated:YES completion:^{
        WJLog(@"打开发布页面");
    }];
}


@end
